Home:ALL Converter>Python file writing error because of "/" in the file name

Python file writing error because of "/" in the file name

Ask Time:2020-02-24T00:44:58         Author:Emre Unsal

Json Formatter

I have a code chunk like this

for track in (results['tracks']):
        track_id_chunk.append(track['uri'])
        print (str(z) + " - " + track['name'])
        try:
            r = requests.get(track['preview_url'], allow_redirects=True)
            open('dataset/'+genres[x]+"/"+str(track['name'])+'.mp3', 'wb').write(r.content)
        except requests.exceptions.RequestException as e:
            print ("---------------------- Couldnt get "+artists[j]+"  -  "+track['name'] + " !!!")
            continue
        z+=1

It downloads 30 seconds samples of artists given externally using spotify API.

The problem is when a song has a "/" in its name ("War Pigs / Luke's Wall - 2014 Remaster" for example) the file operation looks for the directory before "/", fails to find it and throws error:

FileNotFoundError: [Errno 2] No such file or directory: "dataset/metal/War Pigs / Luke's Wall - 2014 Remaster.mp3"

what is the best practice workaround or solution for this problem?

Author:Emre Unsal,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60364500/python-file-writing-error-because-of-in-the-file-name
dzang :

If you are on Linux you can't have slashes in your filename.\nMy suggestion is to replace the character with something else like '-':\n\nstr(track['name']).replace('/', '-')\n",
2020-02-23T16:51:52
yy